<template>
  <div class="container">
    <div v-loading="loading" class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="changerole(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnpermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row.id)">编辑</el-button>
              <el-popconfirm title="确认删除该条数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 放置分页组件 -->
    <el-row type="flex" style="height:60px" align="middle" justify="end">
      <!-- 放置分页组件 -->
      <el-pagination
        :page-size="pageParams.pagesize"
        :current-page="pageParams.page"
        :total="pageParams.total"
        layout="prev, pager, next"
        @current-change="changePage"
      />
    </el-row>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="close">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="roleForm.state"
            size="mini"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="add">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置分配权限弹层 -->
    <el-dialog title="分配权限" :visible.sync="roledialogshow">
      <el-tree
        ref="permissiontree"
        :data="Rolelist"
        :props="defaultProps"
        default-expand-all
        show-checkbox
        :default-checked-keys="permIds"
        node-key="id"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogshow = false">取 消</el-button>
        <el-button type="primary" @click="btnOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { listToTree } from '@/utils/listtotree'
export default {
  name: 'Role',
  data() {
    return {
      userId: null,
      list: [],
      permIds: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 8, // 每页多少条
        total: 0 // 总条数
      },
      showDialog: false,
      roledialogshow: false, // 是否显示分配权限的弹层
      defaultProps: {
        label: 'name'
      },
      Rolelist: [],
      loading: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },

  methods: {
    // 获取角色列表
    async getRoleList() {
      // 发送请求
      const { rows, total } = await getRoleList(this.pageParams)
      console.log(rows)
      this.list = rows // 赋值数据
      this.pageParams.total = total // 赋值总条数
      this.list.forEach(item => { // 遍历数组
        this.$set(item, 'isEdit', false) // 给每条数据添加isEdit和editRow属性
        this.$set(item, 'editRow', {
          // 编辑行数据
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    async add() {
      await this.$refs.roleForm.validate()
      await addRole(this.roleForm)
      // 提示用户
      this.$message.success('添加角色成功')
      // 重新获取数据
      this.getRoleList()
      // 关闭弹层
      this.close()
      // 回到第一页
      // this.pageParams.page = 1
    },
    close() {
      // 重置表单并关闭弹层
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 点击显示行内编辑
    btnEditRow(id) {
      // 找到点击行的数据
      const targetItem = this.list.find(item => item.id === id)
      if (targetItem) {
        // 显示行内编辑
        targetItem.isEdit = true
        // 赋值数据 数据回显
        targetItem.editRow.name = targetItem.name
        targetItem.editRow.description = targetItem.description
        targetItem.editRow.state = targetItem.state
      }
    },
    // 更新角色
    async changerole(row) {
      // 判断内容是否存在
      if (row.editRow.name && row.editRow.description) {
        // 发送请求
        await updateRole({ ...row.editRow, id: row.id })
        // 提示用户
        this.$message.success('修改成功')
        // 修改数据
        // Object.assign(target, source)方法可以用来合并两个对象，这里用作修改数据将row.editRow合并到row中
        // target是要修改的对象，source是修改成什么
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.error('内容不能为空')
      }
    },
    // 确认删除
    async confirmDel(id) {
      await delRole(id)
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    // 渲染分配权限弹层
    async btnpermission(id) {
      this.permIds = [] // 每次点击时先清空清空数组
      this.loading = true
      this.userId = id
      this.Rolelist = listToTree(await getPermissionList(), 0) // 获取树形权限列表
      const { permIds } = await getRoleDetail(id) // 获取角色已有的权限id
      this.permIds = permIds // 赋值
      this.loading = false
      this.roledialogshow = true
    },
    // 提交分配权限
    async btnOK() {
      // this.$refs.permissiontree.getCheckedKeys() 获取选中的id
      await assignPerm({
        id: this.userId,
        permIds: this.$refs.permissiontree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.roledialogshow = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
